package cn.wolfcode.service.impl;

import cn.wolfcode.domain.StrategyComment;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.query.StrategyCommentQuery;
import cn.wolfcode.repository.StrategyCommentRepository;
import cn.wolfcode.service.IStrategyCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IStrategyCommentService strategyCommentService;
    @Override
    public void insert(StrategyComment comment) {
        comment.setId(null);
        repository.save(comment);
    }

    @Override
    public void update(StrategyComment comment) {
        repository.save(comment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> listAll() {
        return repository.findAll();
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //创建查询对象
        Query query = new Query();
        //查询总条数
        long count = template.count(query, StrategyComment.class);
        if (count == 0){
            return Page.empty();
        }
        if (StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }
        Pageable page = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        query.with(page);
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        PageImpl<StrategyComment> strategyComments = new PageImpl<>(list, page, count);
        return strategyComments;
    }

    @Override
    public void commentThumb(String cid, UserInfo userInfo) {
        //查询评论对象,获取点赞id集合
        StrategyComment comment = strategyCommentService.get(cid);
        List<String> list = comment.getThumbuplist();
        //判断获取到的用户id是否在集合中
        //如果在,就是取消点赞 把id在集合中删除 并且点赞数减一
        if (list.contains(userInfo.getId())){
            list.remove(userInfo.getId());
            comment.setThumbupnum(comment.getThumbupnum() - 1);
        }else {//如果不在 就是点赞 把用户id存入集合 点赞数加一
            list.add(userInfo.getId());
            comment.setThumbupnum(comment.getThumbupnum() + 1);
        }
        //更新
        this.update(comment);
    }

}
